<template>
  <el-dialog v-model="dialogVisible" :title="title" width="800px" @close="handleClose">
    <certificate-form ref="formRef" :initial-data="initialData" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import CertificateForm from './CertificateForm.vue'
import { certificateApi } from '@/api/certificateApi'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  type: {
    type: String,
    default: 'add'
  },
  data: {
    type: Object,
    default: () => ({
      id: null,
      category_id: '',
      content: {}
    })
  }
})

const emit = defineEmits(['update:visible', 'success'])

// 对话框标题
const title = computed(() => (props.type === 'add' ? '添加证书' : '编辑证书'))

// 表单引用
const formRef = ref(null)

// 对话框可见性
const dialogVisible = computed({
  get: () => props.visible,
  set: val => emit('update:visible', val)
})

// 初始数据
const initialData = computed(() => ({
  ...props.data
}))

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  if (formRef.value) {
    formRef.value.resetForm()
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    const transformedData = formRef.value.getTransformedData()

    let response;
    if (props.type === 'edit') {
      response = await certificateApi.updateCertificate(props.data.id, transformedData);
    } else {
      response = await certificateApi.createCertificate(transformedData);
    }

    if (response.code === 200) {
      ElMessage.success(props.type === 'edit' ? '更新成功' : '添加成功');
      emit('success')
      handleClose()
    } else {
      ElMessage.error(response.message || '操作失败');
    }
  } catch (error) {
    console.error('Submit form error:', error)
    ElMessage.error('提交失败')
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
